/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import common.ProdQta;
import ejb.interceptors.Profiler;
import entity.Cliente;
import entity.DettaglioOrdine;
import entity.Ordine;
import entity.Prodotto;
import entity.facade.*;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author sflesca
 */
@Stateless
public class OrderManager implements OrderManagerLocal {
    @EJB
    private DettaglioOrdineFacadeLocal dettaglioOrdineFacade;
    @EJB
    private ProdottoFacadeLocal prodottoFacade;
    @EJB
    private OrdineFacadeLocal ordineFacade;
    
    @EJB
    private ClienteFacadeLocal clienteFacade;
    


    /**
     *
     * @param c
     * @param id
     * @param dettaglio
     * @return
     */
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    @Interceptors(Profiler.class)
    @Override
        public Ordine issueOrder(Long idcliente, List<ProdQta> dettaglio) {
        Ordine o = null;
        
        Cliente c = clienteFacade.find(idcliente);
        if (c!=null){
            o = new Ordine();
            o.setCliente(c);
            ordineFacade.create(o);
            List<DettaglioOrdine> l = o.getDettagliordine();
            for (ProdQta pqta:dettaglio){
                DettaglioOrdine dt = new DettaglioOrdine();
                dt.setOrdine(o);
                l.add(dt);
                Prodotto p = prodottoFacade.find(pqta.getProdotto());
                dt.setProdotto(p);
                dt.setQta(pqta.getQta());
                dettaglioOrdineFacade.create(dt);
            }
        }
        System.out.println("effettuato ordine");
        return o;
    }
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    
}
